//
//  ANMineOrderListController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/14.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANMineOrderListController.h"
#import "MineOrderCell.h"
#import "ANOrderInfoController.h"
#import "ANOrderPayController.h"
#import "OrderEntity.h"

@interface ANMineOrderListController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<OrderEntity *> *dataSource;

@property (nonatomic) int pageNo;

@end

@implementation ANMineOrderListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)refreshLoad
{
    self.pageNo = 1;
    [self requestData];
}

- (void)setupSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = kColorF2F2F2;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    WeakSelf
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageNo = 1;
        [weakSelf requestData];
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageNo++;
        [weakSelf requestData];
    }];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MineOrderCell class] forCellReuseIdentifier:@"MineOrderCell"];
}

- (void)setupConstraints
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)requestData
{
    NSString *state = @"";
    if (self.orderState == OrderStateNoPay) {
        state = @"0";
    }
    if (self.orderState == OrderStateNoReceiving) {
        state = @"2";
    }
    if (self.orderState == OrderStateComplete) {
        state = @"3";
    }
    NSDictionary *body = @{
                           @"memberId":UserUtils.shared.vipId,
                           @"state":state,//（0待付款，1待发货，2待收货，3已完成，4关闭(已取消)）
                           @"pageNo":@(self.pageNo),
                           @"pageSize":@20,
                           };
    [URLManager.shareManager getUrlStr:Api_Mine_Order_List parameters:body entityClass:[OrderListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                OrderListEntity *data = baseEntity.data;
                if (self.pageNo == 1) {
                    [self.dataSource removeAllObjects];
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView.mj_footer resetNoMoreData];
                    if (data.data.count < 20) {
                        self.tableView.mj_footer.alpha = 0;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                else {
                    if (data.data.count < 20) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                }
                [self.dataSource addObjectsFromArray:data.data];
                [self.tableView reloadData];
            }
            else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)changeStateRequest:(OrderEntity *)orderEntity
{
    NSString *fieldValue = @"";
    NSString *fieldName = @"";
    if (orderEntity.state.intValue == 2) { // 确认收货
        fieldValue = @"3";
        fieldName = @"state";
    }
    if (orderEntity.state.intValue == 3 || orderEntity.state.intValue == 4) { // 删除
        fieldValue = @"1";
        fieldName = @"deleteFlag";
    }
    [MBProgressHUD showActivityMessage:nil];
    NSDictionary *body = @{
                           @"id":orderEntity.orderId,
                           @"fieldName":fieldName,
                           @"fieldValue":fieldValue,
                           };
    [URLManager.shareManager postUrlStr:Api_Order_State_Edit parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [MBProgressHUD showSuccess:responseObj[@"message"]];
                self.pageNo = 1;
                [self requestData];
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderEntity *entity = self.dataSource[indexPath.row];
    MineOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineOrderCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.canSelect = NO;
    cell.orderEntity = entity;
    WeakSelf
    cell.changeStateHandler = ^{
        [weakSelf changeStateRequest:entity];
    };
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderEntity *entity = self.dataSource[indexPath.row];
    ANOrderInfoController *vc = [[ANOrderInfoController alloc] init];
    vc.orderId = entity.orderId;
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kWidth(210);
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
